package com.cloud.sample.job;

import com.cloud.common.elasticsearch.ElasticsearchSupport;
import com.cloud.sample.index.IndexProduct;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class ESIndexJob extends IJobHandler implements ApplicationRunner {

    @Autowired
    private ElasticsearchSupport elasticsearchSupport;

    @Override
    @XxlJob("CreateIndexHandler")
    public void execute() {
        String param = XxlJobHelper.getJobParam();
        log.info("param={}", param);
        try {
            createIndex();
            XxlJobHelper.handleSuccess();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            XxlJobHelper.log(e);
            XxlJobHelper.handleFail();
        }
    }

    @Override
    public void run(ApplicationArguments args) {
        // createIndex();
    }

    private void createIndex() {
        String indexDate = elasticsearchSupport.indexYear(new Date());
        elasticsearchSupport.createIndex(IndexProduct.class, indexDate);
    }
}
